import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:new_yuqib_app/yqbConfig/color_theme.dart';

import 'controller.dart';

///验证码按钮
class CodeBtnWidget extends StatefulWidget {
  const CodeBtnWidget({super.key});

  @override
  State<CodeBtnWidget> createState() => _CodeBtnWidgetState();
}

class _CodeBtnWidgetState extends State<CodeBtnWidget> {
  Timer? _timer;
  int codeSeconds = 60;
  String get codeText => codeSeconds >0 && codeSeconds < 60 ? "$codeSeconds s" : "获取验证码";

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (codeSeconds > 0) {
          codeSeconds--;
        } else {
          isOnTap = true;
          codeSeconds = 60;
          _timer!.cancel();
        }
      });
    });
  }

  bool isOnTap = true;

  var controller = Get.find<LoginViewController>();
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: (){
        //防抖
        if(!isOnTap && codeSeconds<60)return;
        isOnTap = false;
        controller.sendCode(_startTimer);
      },
      child: Container(
        height: 44,
        alignment: Alignment.center,
        width: 106,
        decoration: BoxDecoration(
          border: Border.all(width: 1, color: ColorTheme.borderColor),
          borderRadius: BorderRadius.circular(8),
        ),
        child:  Text(
          codeText,
          style: TextStyle(
            fontWeight: FontWeight.w500,
            color:codeSeconds==60 ? ColorTheme.buttonTextColor:ColorTheme.secondaryTextColor,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    if(_timer !=null) _timer!.cancel();
    super.dispose();
  }
}
